import { useEffect, useState } from 'react';
import { Message, Input, Form, Box, Button, Card, DatePicker, Radio, Upload, Table, Rating } from '@alifd/next';
import type { UploadProps } from '@alifd/next/types/upload';
import { Moment } from 'moment';
import styles from './index.module.css';
import EditableCell from './EditableCell';
import { RadioGroup } from '@alifd/next/types/radio/radio-group';
import ChooseFeel from './ChooseFeel';

const FormItem = Form.Item;

const formItemLayout = {
  colSpan: 12,
};

export interface DataSource {
  name?: string;
  category?: string;
  date?: Moment[];
  type?: string;
  pic?: UploadProps[];
  desc?: string;
}

export interface BasicFormProps {
  dataSource?: DataSource;
  onSubmit?: (values: BasicFormProps) => Promise<void>;
  onCancel?: () => void;
}

const DEFAULT_DATA: DataSource = {
  type: 'private',
};
function pailie(list, prePrefix?) {
  let prefix = prePrefix || [];
  let result = [];
  for (let i = 0; i < list.length; i++) {
    let temp = [...prefix, list[i]]
    result = result.concat(pailie(list.slice(i + 1), temp));
    result.push(temp);
  }
  if (!prePrefix) {
    return result.filter((item: any) => {
      return item.length > 1;
    }).sort((item1, item2) => {
      console.log(item1, item2)
      return item1.length > item2.length ? 1 : -1;
    });
  } else {
    return result;
  }
}
const DEFAULT_ON_SUBMIT = (values: BasicFormProps, errors: []): void => {
  if (errors) {
    console.log('errors', errors);
    return;
  }
  console.log('values:', values);
  Message.success('提交成功');
};

const BasicForm: React.FC<BasicFormProps> = (props: BasicFormProps): JSX.Element => {
  const {
    onSubmit = DEFAULT_ON_SUBMIT,
    onCancel = (): void => { },
  } = props;
  const [robotList, setRobotList] = useState([]);
  const [dataSource, setDataSource] = useState([
    {
      choose: '选择',
      feel: 0,
      score: 0,
      type: 'human',
      id: new Date().getTime()
    },
  ]);

  const propsConf = {
    className: 'next-myclass',
    style: { background: 'rgba(0,0,0,0.02)' },
    onDoubleClick: () => {
      console.log('doubleClicked');
    },
  };
  const choosePropsConf = {
    className: 'next-choose',
    style: { background: 'black', color: 'white' },
    onDoubleClick: () => {
      console.log('doubleClicked');
    },
  };
  const setRowProps = (record, index) => {
    if (record.type === 'robot') {
      return propsConf;
    }
  };
  const setCellProps = (rowIndex, colIndex, dataIndex, record) => {

  };
  const getRobotList = (datas) => {
    const humans = datas.filter(item => {
      return item.type == 'human';
    });
    let humanIds = humans.map(item => {
      return item.id;
    }).sort();

    let robotChooses = pailie(humanIds);
    let alreadyMaps = {};
    datas.forEach(element => {
      alreadyMaps[element.id] = element;
    });
    // 自动生成决策
    let zidongs = robotChooses.map((itemIds: any) => {
      let itemId = itemIds.join('_');
      if (alreadyMaps[itemId]) {
        return alreadyMaps[itemId];
      } else {
        return {
          choose: '同时 ' + itemIds.map(chooseId => {
            return alreadyMaps[chooseId].choose
          }).join(' 和 '),
          feel: 0,
          score: 0,
          type: 'robot',
          id: itemIds
        }
      }
    });
    return zidongs;
  }
  useEffect(() => {
    setRobotList(getRobotList(dataSource));
  }, [dataSource]);
  return (
    <Card free>
      <Card.Content>
        <Table dataSource={[...dataSource, ...robotList]} rowProps={setRowProps} cellProps={setCellProps}>
          <Table.Column style={{
            width: '500px'
          }} title={() => {
            return <div><Button onClick={() => {
              let list = [
                {
                  choose: '选择',
                  feel: 0,
                  score: 0,
                  type: 'human',
                  id: new Date().getTime()
                },
                ...dataSource
              ];
              setDataSource(list);
            }}>添加选择</Button></div>
          }} dataIndex="choose" cell={(value, index, record) => {
            if (record.type == 'human') {
              return <Input value={value} onChange={(value) => {
                dataSource[index] = {
                  ...dataSource[index],
                  choose: value
                }
                setDataSource([
                  ...dataSource
                ]);
              }} onBlur={(e) => {
                let value = e.target.value;
                if (value.trim() == '') {
                  dataSource.splice(index, 1);
                  setDataSource([
                    ...dataSource
                  ]);
                }
              }} />;
            } else {
              return value;
            }
          }} />
          <Table.Column style={{
            width: '400px'
          }} title="我的感受是什么" dataIndex="feel" cell={(value, index, record) => {
            return <ChooseFeel value={value} onChange={(value) => {
              if (record.type == 'human') {
                dataSource[index] = {
                  ...dataSource[index],
                  feel: value
                }
                setDataSource([
                  ...dataSource
                ]);
              } else {
                let robotIndex = index - dataSource.length;
                robotList[robotIndex] = {
                  ...robotList[robotIndex],
                  feel: value
                }
                setRobotList([
                  ...robotList
                ]);
              }
              
            }}></ChooseFeel>
          }} />
          <Table.Column title="心情愉悦程度" dataIndex="score" cell={(value, index, record) => {
            return <Rating  value={value} size="large" onChange={(value) => {
              if (record.type == 'human') {
                dataSource[index] = {
                  ...dataSource[index],
                  score: value
                }
                setDataSource([
                  ...dataSource
                ]);
              } else {
                let robotIndex = index - dataSource.length;
                robotList[robotIndex] = {
                  ...robotList[robotIndex],
                  score: value
                }
                setRobotList([
                  ...robotList
                ]);
              }
            }}/>;
          }} />
        </Table>
      </Card.Content>
    </Card>
  );
};

export default BasicForm;
